/**
 * This script will include all business logic for this application.
 * This script depend of:
 * @author Mihail Merkov
 * @dependOf
 *   jQuery  >= 2.0.3 library {@link http://jquery.com/download/}
 *   jquery.json-2.4 plugin {@link https://code.google.com/p/jquery-json/}
 *   ----------------------------------------------------------------------------------------------------------------
 */

var TennisTour = TennisTour || {};
TennisTour.Model = {};
TennisTour.Service = {};


/**
 * This represent a game into a match
 * @type Enum
 */
TennisTour.Model.GameEnum = {};
TennisTour.Model.GameEnum.FIRST     =   "FIRST";
TennisTour.Model.GameEnum.SECOND    =   "SECOND";
TennisTour.Model.GameEnum.THIRD     =   "THIRD";

/**
 * This represent whether the player in a match is a
 * host or guest
 * @type {WinnerEnum}
 */
TennisTour.Model.WinnerEnum = {};
TennisTour.Model.WinnerEnum.HOST    =   "HOST";
TennisTour.Model.WinnerEnum.GUEST   =   "GUEST";

/**
 * This represent which stage og tournament is a current match
 * @type {StageOfTournamentEnum}
 */
TennisTour.Model.StageOfTournamentEnum = {};
TennisTour.Model.StageOfTournamentEnum.GROUPSTAGE   = "GROUPSTAGE";
TennisTour.Model.StageOfTournamentEnum.SECONDSTAGE  = "SECONDSTAGE";
TennisTour.Model.StageOfTournamentEnum.QUARTERFINAL = "QUARTERFINAL";
TennisTour.Model.StageOfTournamentEnum.SEMIFINAL    = "SEMIFINAL";
TennisTour.Model.StageOfTournamentEnum.THIRD_PLACE  = "THIRD_PLACE";
TennisTour.Model.StageOfTournamentEnum.FINAL        = "FINAL";

/**
 * Player object
 * @constructor object { id : int, name : string, jobPosition: string, pathToPicture : string }
 */
TennisTour.Model.Player = function (object) {
    this.id = null;
    this.name = "";
    this.jobPosition = "";
    this.pathToPicture = "";
    this.numberWinners = 0;
    this.numberLosses = 0;
    this.differencePoints = 0;


    // calling initialize object
    init(this, object);

    /**
     * Initialize current object
     * @scope private
     * @param thisObject
     * @param inputObject
     */
    function init(thisObject, inputObject) {
        var UNDEFINED = 'undefined';

        if (typeof(inputObject) == UNDEFINED) {
            return;
        }
        if (typeof(inputObject.id) !== UNDEFINED) {
            thisObject.id = inputObject.id;
        }
        if (typeof(inputObject.name) !== UNDEFINED) {
            thisObject.name = inputObject.name;
        }
        if (typeof(inputObject.jobPosition) !== UNDEFINED) {
            thisObject.jobPosition = inputObject.jobPosition;
        }
        if (typeof(inputObject.pathToPicture) !== UNDEFINED) {
            thisObject.pathToPicture = inputObject.pathToPicture;
        }
        if (typeof(inputObject.numberWinners) !== UNDEFINED) {
            thisObject.numberWinners = inputObject.numberWinners;
        }
        if (typeof(inputObject.numberLosses) !== UNDEFINED) {
            thisObject.numberLosses = inputObject.numberLosses;
        }
        if (typeof(inputObject.obtainedPoints) !== UNDEFINED && typeof(inputObject.madePoints) !== UNDEFINED) {
            thisObject.differencePoints = calculateDifference(inputObject.madePoints, inputObject.obtainedPoints);
        }
    }

    /**
     * Create appropriate sign of difference
     * @scope private
     * @param taken
     * @param get
     * @returns {string}
     */
    function calculateDifference(taken, get) {
        var sign = (taken - get) < 0 ? '' : '+';
        var difference = (taken - get);
        return difference != 0 ? sign + difference : difference;
    }
};

/**
 * Create a Player object from a JSON param object.
 * It set a Player's properties only if the object includes this properties
 * @scope static
 * @param json
 * @returns {TennisTour.Model.Player}
 */
TennisTour.Model.Player.parseFromJSON = function(json) {
    return new TennisTour.Model.Player(jQuery.parseJSON(json));
};

/**
 * GroupStats Object
 * @constructor object { id : int, player : Player, points : int, takenPoints : int,
 *      getPoints : int, countVictories : int, countLosses : int }
 */
TennisTour.Model.GroupStats = function (object) {
    this.id = null;
    this.player = new TennisTour.Model.Player();
    this.points = 0;
    this.takenPoints = 0;
    this.getPoints = 0;
    this.countVictories = 0;
    this.countLosses = 0;
    this.difference = 0;

    // calling initializing of object
    init(this, object);

    /**
     * Initialize this object from input object
     * @scope private
     * @param myObject
     * @param inputObject
     */
    function init(myObject, inputObject) {
        var UNDEFINED = 'undefined';

        if (typeof(inputObject) == UNDEFINED) {
            return;
        }
        if (typeof(inputObject.id) !== UNDEFINED) {
            myObject.id = inputObject.id;
        }
        if (typeof(inputObject.player) !== UNDEFINED) {
            myObject.player = new TennisTour.Model.Player(inputObject.player);
        }
        if (typeof(inputObject.points) !== UNDEFINED) {
            myObject.points = inputObject.points;
        }
        if (typeof(inputObject.takenPoints) !== UNDEFINED) {
            myObject.takenPoints = inputObject.takenPoints;
        }
        if (typeof(inputObject.getPoints) !== UNDEFINED) {
            myObject.getPoints = inputObject.getPoints;
        }
        if (typeof(inputObject.countVictories) !== UNDEFINED) {
            myObject.countVictories = inputObject.countVictories;
        }
        if (typeof(inputObject.countLosses) !== UNDEFINED) {
            myObject.countLosses = inputObject.countLosses;
        }
        myObject.difference = calculateDifference(myObject.takenPoints, myObject.getPoints);
    }

    /**
     * Create appropriate sign of difference
     * @scope private
     * @param taken
     * @param get
     * @returns {string}
     */
    function calculateDifference(taken, get) {
        var sign = (taken - get) < 0 ? '' : '+';
        var difference = (taken - get);
        return difference != 0 ? sign + difference : difference;
    }
};

/**
 * Create a GroupStats object from a JSON param object.
 * It set a GroupStats's properties only if the object includes this properties
 * @scope static
 * @param json
 * @returns TennisTour.Model.GroupStats
 */
TennisTour.Model.GroupStats.parseFromJSON = function(json) {
    return new TennisTour.Model.GroupStats(jQuery.parseJSON(json));
};


TennisTour.Model.Group = function (object) {
    this.name = "";
    this.CollectionGroupStats = [];

    // calling initializing of object
    init(this, object);

    /**
     * Initialize this object from input object
     * @scope private
     * @param thisObject
     * @param inputObject
     */
    function init(thisObject, inputObject) {
        var UNDEFINED = 'undefined';

        if (typeof(inputObject) == UNDEFINED) {
            return;
        }
        if (typeof(inputObject.name) !== UNDEFINED) {
            thisObject.name = inputObject.name;
        }
        if ((typeof(inputObject.stats) !== UNDEFINED && jQuery.isArray(inputObject.stats))) {
            for (var i = 0; i < inputObject.stats.length; i++) {
                thisObject.CollectionGroupStats[i] = new TennisTour.Model.GroupStats(inputObject.stats[i]);
            }
        }
    }
};

/**
 * Create a Group object from a JSON param object.
 * It set a Group's properties only if the object includes this properties
 * @scope static
 * @param json
 * @returns {TennisTour.Model.Group}
 */
TennisTour.Model.Group.parseFromJSON = function(json) {
    return new TennisTour.Model.Group(jQuery.parseJSON(json));
};

/**
 * Result Object
 * @param object
 * @constructor object {hostScore : int, guestScore : int, game : str}
 */
TennisTour.Model.Result = function(object) {
    this.matchId = null;
    this.hostScore = null;
    this.guestScore = null;
    /** @var GameEnum **/
    this.game = "";

    // calling initializing of object
    init(this, object);

    /**
     * Initialize this object from input object
     * @scope private
     * @param thisObject
     * @param inputObject
     */
    function init(thisObject, inputObject) {
        var UNDEFINED = 'undefined';

        if (typeof(inputObject) == UNDEFINED) {
            return;
        }
        if (typeof(inputObject.matchId) !== UNDEFINED) {
            thisObject.matchId = inputObject.matchId;
        }
        if (typeof(inputObject.hostScore) !== UNDEFINED) {
            thisObject.hostScore = inputObject.hostScore;
        }
        if (typeof(inputObject.guestScore) !== UNDEFINED) {
            thisObject.guestScore = inputObject.guestScore;
        }
        if (typeof(inputObject.game) !== UNDEFINED) {
            thisObject.game = inputObject.game;
        }
    }
};

/**
 * Create a Result object from a JSON param object.
 * It set a Result's properties only if the object includes this properties
 * @scope static
 * @param json
 * @returns {TennisTour.Model.Result}
 */
TennisTour.Model.Result.parseFromJSON = function(json) {
    return new TennisTour.Model.Result(jQuery.parseJSON(json));
};

/**
 * Represent a Match
 * @param object
 * @constructor
 */
TennisTour.Model.Match = function(object) {
    this.id = null;
    this.hostPlayer = new TennisTour.Model.Player();
    this.guestPlayer = new TennisTour.Model.Player();
    /** @type value from StageOfTournamentEnum **/
    this.stageOfTournament = "";
    /** @type value from WinnerEnum **/
    this.winner = null;
    /** @type value from Date **/
    this.date = null;
    /** @type array from Result **/
    this.CollectionResults = null;

    // calling initializing of object
    init(this, object);

    /**
     * Initialize this object from input object
     * @scope private
     * @param thisObject
     * @param inputObject
     */
    function init(thisObject, inputObject) {
        var UNDEFINED = 'undefined';

        if (typeof(inputObject) == UNDEFINED) {
            return;
        }
        if (typeof(inputObject.id) !== UNDEFINED) {
            thisObject.id = inputObject.id;
        }
        if (typeof(inputObject.playerHost) !== UNDEFINED) {
            thisObject.hostPlayer = new TennisTour.Model.Player(inputObject.playerHost);
        }
        if (typeof(inputObject.playerGuest) !== UNDEFINED) {
            thisObject.guestPlayer = new TennisTour.Model.Player(inputObject.playerGuest);
        }
        if (typeof(inputObject.winner) !== UNDEFINED) {
            thisObject.winner = inputObject.winner;
        }
        if (typeof(inputObject.stageOfTournament) !== UNDEFINED) {
            thisObject.stageOfTournament = inputObject.stageOfTournament;
        }
        if (typeof(inputObject.date) !== UNDEFINED && inputObject.date != null) {
            thisObject.date = new Date(inputObject.date);
        }
        if (typeof(inputObject.results) !== UNDEFINED && jQuery.isArray(inputObject.results)) {
            thisObject.CollectionResults = [];
            for (var i = 0; i < inputObject.results.length; i++) {
                thisObject.CollectionResults[i] = new TennisTour.Model.Result(inputObject.results[i]);
            }
        }
    }
};

/**
 * Create a Result object from a JSON param object.
 * It set a Result's properties only if the object includes this properties
 * @scope static
 * @param json
 * @returns {TennisTour.Model.Match}
 */
TennisTour.Model.Match.parseFromJSON = function(json) {
    return new TennisTour.Model.Match(jQuery.parseJSON(json));
};

/**
 * This represent the service class for a Group model
 * @constructor void
 */
TennisTour.Service.GroupService = function() {
    /**
     * Parse a json into array from Group objects
     * @param json Retrieve array from groups by JSON object
     * @returns array from Groups
     */
    this.parseArrayToGroupsFromJSON = function(json) {
        var UNDEFINED = 'undefined';
        var jsonObject = jQuery.parseJSON(json);
        var collectionGroups = [];

        if (typeof(jsonObject.groups) !== UNDEFINED && jQuery.isArray(jsonObject.groups)) {
            for (var i = 0; i < jsonObject.groups.length; i++) {
                collectionGroups[i] = new TennisTour.Model.Group(jsonObject.groups[i]);
            }
        }

        return collectionGroups;
    };

    /**
     *
     * @param input {deployId : string, collectionGroup : array from Group}
     */
    this.showAllGroups = function(input) {
        var UNDEFINED = 'undefined';
        var groupsPattern = '';

        if (typeof(input.deployId) == UNDEFINED || typeof(input.collectionGroup) == UNDEFINED ||
             !jQuery.isArray(input.collectionGroup)) {
            return;
        }

        for (var i = 0; i < input.collectionGroup.length; i++) {
            groupsPattern += createModelOfGroup(input.collectionGroup[i])
        }

        jQuery('#' + input.deployId).html(groupsPattern);

        // Create On Hover EVENT to show popup of a player, when some picture is hover by mouse
        $('.picture').hover(function(){
            var $srcPicture = $(this).find('img').attr('src');
            var name = $(this).find('.name').text();
            var job = $(this).find('.job').text();

            $(this).on('mousemove',function(e){
                var $pageX = e.pageX;
                var $pageY = e.pageY;
                if($pageY > ($('html').height() - 108)){
                    $pageY = $pageY - 110;
                }
                $('.infoPlayer').css(
                    {
                        position:'absolute',
                        top: $pageY,
                        left: $pageX
                    }).addClass('backgroundInfoPlayer')
            });
            $('.picturePlayer').append('<img src="' + $srcPicture + '"/>');
            $('.picturePlayer img').css({width:'120px'}).queue(function() {
                $('.infoPlayer').height($('.picturePlayer img').height());
                $(this).dequeue();
            });



            $('.info').append("<span> Name: " + name + " </span>").append("<span> Job: " + job + "</span>");
        }, function(){
            $('.infoPlayer').css({
                position:'absolute',
                top: '0',
                left: '0'
            }).removeClass('backgroundInfoPlayer');
            $('.picturePlayer img').remove();
            $('.info').find('span:last').remove();
            $('.info').find('span:first').remove();
        });

        /**
         * Create a HTML code of a group which represent data from a {@link TennisTour.Model.Group}
         * @param group {TennisTour.Model.Group}
         * @returns string
         */
        function createModelOfGroup(group) {
            var pattern = '<section class="contentTable clearfix"> <p>Group ' + group.name + '</p>' +
                '<table class="span6 table-striped table-bordered"> <thead><tr>' +
                '<th>Position</th><th>Player</th><th>Victories</th>' +
                '<th>Loses</th><th>Difference</th><th>Made Points</th><th>Received Points</th>' +
                '</tr></thead><tbody>';

            for (var i = 0; i < group.CollectionGroupStats.length; i++) {
                var groupStats = new TennisTour.Model.GroupStats(group.CollectionGroupStats[i]);
                pattern += '<tr><td>' + (i+1) + '</td>' +
                    createModelOfPersonPopup(groupStats.player) +
                    '<td>' + groupStats.countVictories + '</td>' +
                    '<td>' + groupStats.countLosses + '</td><td>' + groupStats.difference + '</td>' +
                    '<td>' + groupStats.takenPoints + '</td>' +
                    '<td>' + groupStats.getPoints + '</td></tr>';
            }

            pattern += '</tbody></table></section>';

            /**
             * Create a HTML code of popup, for current {@link TennisTour.Model.GroupStats} of
             * a {@link TennisTour.Model.Group}
             * @param player {TennisTour.Model.Player}
             * @returns {string}
             */
            function createModelOfPersonPopup(player) {
                return '<td class="picture">' +
                    '<img src="' + player.pathToPicture + '" />' +
                    '<span class="name" style="display: none;">' + player.name + '</span>' +
                    '<span class="job" style="display: none";>' + player.jobPosition + '</span></td>';
            }

            return pattern;
        }
    };

    /**
     * Show Draws
     * @param inputObject Object { FINAL : Match, THIRD_PLACE : Match, SEMIFINAL : [Match, Match]}
     */
    this.showDraws = function(inputObject) {
        var UNDEFINED = 'undefined';

        if (typeof(inputObject.FINAL) != UNDEFINED && inputObject.FINAL != null) {
            var finalMatch = new TennisTour.Model.Match(inputObject.FINAL[0]);
            fillMatch(finalMatch, '.final');
            if (finalMatch.winner != null) {
                if (finalMatch.winner == TennisTour.Model.WinnerEnum.HOST) {
                    jQuery('.winnerPost>img:last-of-type').attr('src', finalMatch.hostPlayer.pathToPicture);
                    jQuery('.winnerPost>span').text(finalMatch.hostPlayer.name);
                } else {
                    jQuery('.winnerPost>img:last-of-type').attr('src', finalMatch.guestPlayer.pathToPicture);
                    jQuery('.winnerPost>span').text(finalMatch.guestPlayer.name);
                }
                jQuery('.winnerPost').show();
            }
        }
        if (typeof(inputObject.THIRD_PLACE) != UNDEFINED && inputObject.THIRD_PLACE != null) {
            fillMatch(new TennisTour.Model.Match(inputObject.THIRD_PLACE[0]), '.thirdPlace');
        }
        if (typeof(inputObject.SEMIFINAL) != UNDEFINED && inputObject.SEMIFINAL != null) {
            for (var i = 0; i < inputObject.SEMIFINAL.length; i++) {
                var deployCss = '.semiFinals.p' + (i + 1);
                fillMatch(new TennisTour.Model.Match(inputObject.SEMIFINAL[i]), deployCss);
            }
        }

        if (typeof(inputObject.QUARTERFINAL) != UNDEFINED && inputObject.QUARTERFINAL != null) {
            for (var i = 0; i < inputObject.QUARTERFINAL.length; i++) {
                var deployCss = '.quarterFinals.p' + (i + 1);
                fillMatch(new TennisTour.Model.Match(inputObject.QUARTERFINAL[i]), deployCss);
            }
        }

        jQuery('.draws').show();

        /**
         * Fill each Mach in draws
         * @param match
         * @param deployPositionCss
         */
        function fillMatch(match, deployPositionCss) {
            // Add picture to Players and set styles if the Match is already played
            jQuery(deployPositionCss).find('.hPlayer').find('img').attr('src', match.hostPlayer.pathToPicture);
            jQuery(deployPositionCss).find('.gPlayer').find('img').attr('src', match.guestPlayer.pathToPicture);

            jQuery(deployPositionCss).find('figure:first>span').text(createShortName(match.hostPlayer.name));
            jQuery(deployPositionCss).find('figure:last>span').text(createShortName(match.guestPlayer.name));

            if (match.winner != null) {
                if (match.winner == TennisTour.Model.WinnerEnum.HOST) {
                    jQuery(deployPositionCss).find('figure:first>span').addClass('winner');
                    jQuery(deployPositionCss).find('figure:last>span').addClass('losses');
                } else {
                    jQuery(deployPositionCss).find('figure:first>span').addClass('losses');
                    jQuery(deployPositionCss).find('figure:last>span').addClass('winner');
                }
            }

            // Add results and add style if the Match is already played
            if (match.CollectionResults != null) {
                for (var i = 0; i < match.CollectionResults.length; i++) {
                    var host = '';
                    var guest = '';
                    if (match.CollectionResults[i].hostScore > match.CollectionResults[i].guestScore) {
                        host = 'winner';
                        guest = 'losses';
                    } else {
                        host = 'losses';
                        guest = 'winner';
                    }
                    jQuery(deployPositionCss).find('.results tr:nth-child('+ (i+1) +') .hostScore')
                        .text(match.CollectionResults[i].hostScore).addClass(host);
                    jQuery(deployPositionCss).find('.results tr:nth-child('+ (i+1) +') .guestScore')
                        .text(match.CollectionResults[i].guestScore).addClass(guest);
                }
            }

            /**
             * Crate short name.
             * Example Mihail Merkov --> M. Merkov
             * @param name
             * @returns {string}
             */
            function createShortName(name) {
                var names = name.split(' ');
                return name[0].substring(0, 1) + '. ' + names[1];;
            }
        }
    }
};

TennisTour.Service.MatchesService = function(){

    /**
     * object {matchesToday : [Match], matchesYesterday : [Match]}
     * @param object
     */
    this.playedMatches = function(object) {
        var noGamesLabel = '<p>There were no games</p>';

        if (object.matchesToday.length == 0) {
            jQuery('.matchesToday').append(noGamesLabel);
        } else {
            var pattern = '';
            for (var i = 0; i < object.matchesToday.length; i++) {
                pattern += fillMatch(new TennisTour.Model.Match(object.matchesToday[i]));
            }
            jQuery('.matchesToday').append(pattern).find('.results tr').addClass('fix_height');
        }

        if (object.matchesYesterday.length == 0) {
            jQuery('.matchesYesterday').append(noGamesLabel);
        } else {
            var pattern = '';
            for (var i = 0; i < object.matchesYesterday.length; i++) {
                pattern += fillMatch(new TennisTour.Model.Match(object.matchesYesterday[i]));
            }
            jQuery('.matchesYesterday').append(pattern).find('.results tr').addClass('fix_height');
        }

        function fillMatch(match) {
            var hPlayerCssClass = match.winner == null ? '' : match.winner == TennisTour.Model.WinnerEnum.HOST ? 'winner' : 'losses';
            var gPlayerCssClass = match.winner == null ? '' : match.winner == TennisTour.Model.WinnerEnum.GUEST ? 'winner' : 'losses';
            var matchPattern = '<article class="match"><figure><div class="hPlayer">';
            matchPattern += '<img src="' + match.hostPlayer.pathToPicture + '"/>';
            matchPattern += '</div><span class="playerName ' + hPlayerCssClass + '">' + createShortName(match.hostPlayer.name) + '</span>';
            matchPattern += '</figure><figure><div class="gPlayer"><img src="';
            matchPattern += match.guestPlayer.pathToPicture + '"/></div>';
            matchPattern += '<span class="playerName ' + gPlayerCssClass + '">' + createShortName(match.guestPlayer.name) + '</span>';
            matchPattern += '</figure><table class="results">';

            if (match.CollectionResults != null) {
                for (var i = 0; i < match.CollectionResults.length; i++) {
                    var result = match.CollectionResults[i];
                    if (result.hostScore > result.guestScore) {
                        matchPattern += '<tr><td><span class="hostScore winner">' + result.hostScore + '</span> : ';
                        matchPattern += '<span class="guestScore losses">' + result.guestScore + '</span>';
                    } else {
                        matchPattern += '<tr><td><span class="hostScore losses">' + result.hostScore + '</span> : ';
                        matchPattern += '<span class="guestScore winner">' + result.guestScore + '</span>';
                    }
                }
                if (match.CollectionResults.length == 2) {
                    matchPattern += '<tr><td><span class="hostScore"></span> : <span class="guestScore"></span></td></tr>';
                }
            } else {
                matchPattern += '<tr><td><span class="hostScore"></span> : <span class="guestScore"></span></td></tr>' +
                    '<tr><td><span class="hostScore"></span> : <span class="guestScore"></span></td></tr>' +
                    '<tr><td><span class="hostScore"></span> : <span class="guestScore"></span></td></tr>';
            }

            matchPattern += '</table></article>';

            return matchPattern;
        }


        /**
        * Crate short name.
        * Example Mihail Merkov --> M. Merkov
        * @param name
        * @returns {string}
        */
        function createShortName(name) {
            var names = name.split(' ');
            return finalName = name[0].substring(0, 1) + '. ' + names[1];
        }
    };

    /**
     * Manage manipulation of an Match
     * @param match {TennisTour.Model.Match}
     */
    this.manageMatch = function(match) {
        var EMPTY                   =   "";
        var $modal                  =   jQuery('#manageMatch');
        var $id                     =   jQuery('[name="id"]', $modal);
        var $hostPlayerPicture      =   jQuery('.hostPlayerPicture', $modal);
        var $guestPlayerPicture     =   jQuery('.guestPlayerPicture', $modal);
        var $hostScoreFirstGame     =   jQuery('input[name="hostScoreFGame"]',  $modal);
        var $guestScoreFirstGame    =   jQuery('input[name="guestScoreFGame"]',  $modal);
        var $hostScoreSecondGame    =   jQuery('input[name="hostScoreSGame"]',  $modal);
        var $guestScoreSecondGame   =   jQuery('input[name="guestScoreSGame"]',  $modal);
        var $hostScoreThirdGame     =   jQuery('input[name="hostScoreTGame"]',  $modal);
        var $guestScoreThirdGame    =   jQuery('input[name="guestScoreTGame"]',  $modal);
        var $dateOfMatch            =   jQuery('[name="date"]', $modal);
        var $winner                 =   jQuery('[name="winner"]');
        var winnerEnum              =   TennisTour.Model.WinnerEnum;
        var isSetDateForMatch       =   false;

        init();

        function clearModalMatch() {
            $id.val(EMPTY);

            $hostPlayerPicture.empty();
            $guestPlayerPicture.empty();

            $hostScoreFirstGame.val(EMPTY);
            $guestScoreFirstGame.val(EMPTY);
            $hostScoreSecondGame.val(EMPTY);
            $guestScoreSecondGame.val(EMPTY);
            $hostScoreThirdGame.val(EMPTY);
            $guestScoreThirdGame.val(EMPTY);

            $dateOfMatch.val(EMPTY);
            $winner.val(EMPTY);

            jQuery(".closeBtn", ".close").unbind('click');
        }

        function fillDataInModalMatch() {
            $id.val(match.id);

            var hostPicturePath = match.hostPlayer.pathToPicture;
            var guestPicturePath = match.guestPlayer.pathToPicture;

            $hostPlayerPicture.append('<img style="height:130px;" src="' + hostPicturePath + '"/>');
            $guestPlayerPicture.append('<img style="height:130px;" src="' + guestPicturePath + '"/>');

            if (match.date != null) {
                isSetDateForMatch = true;
                $dateOfMatch.val($.datepicker.formatDate("mm/dd/yy", match.date));
            }
        }

        function isValid(event) {
            var isResultsEmpty = false;
            var errorMessages = "";

            if ($dateOfMatch.val() == EMPTY && !isSetDateForMatch) {
                errorMessages += "You did not specify any date in the match.\n";
                alert(errorMessages);
                event.preventDefault();
                return false;
            }

            if ($hostScoreFirstGame.val() == EMPTY && $guestScoreFirstGame.val() == EMPTY &&
                $hostScoreSecondGame.val() == EMPTY && $guestScoreSecondGame.val() == EMPTY){
                isResultsEmpty = true;
            }

            if ($winner.val() != EMPTY && isResultsEmpty == true) {
                errorMessages += "You did not specify any result, but you are pointed a winner.\n";
                alert(errorMessages);
                event.preventDefault();
                return false;
            } else if ($winner.val() == EMPTY && isResultsEmpty == false) {
                errorMessages += "You did not specify winner, but you are enter results.\n";
                alert(errorMessages);
                event.preventDefault();
                return false;
            } else if ($winner.val() != EMPTY && isResultsEmpty == false) {
                if ($hostScoreFirstGame.val() != EMPTY && $guestScoreFirstGame.val() != EMPTY &&
                    $hostScoreSecondGame.val() != EMPTY && $guestScoreSecondGame.val() != EMPTY) {

                    var resultFGameHost = parseInt($hostScoreFirstGame.val());
                    var resultFGameGuest = parseInt($guestScoreFirstGame.val());
                    var resultSGameHost = parseInt($hostScoreSecondGame.val());
                    var resultSGameGuest = parseInt($guestScoreSecondGame.val());

                    if (resultFGameHost == resultFGameGuest || resultSGameHost == resultSGameGuest) {
                        errorMessages += "Result is incorrect. Please fix it.";
                        alert(errorMessages);
                        event.preventDefault();
                        return false;
                    }

                    var firstGameWinner = resultFGameGuest > resultFGameHost ? winnerEnum.GUEST : winnerEnum.HOST;
                    var secondGameWinner = resultSGameGuest > resultSGameHost ? winnerEnum.GUEST : winnerEnum.HOST;

                    if (firstGameWinner == secondGameWinner && firstGameWinner != $winner.val()) {
                        errorMessages += "A mismatch between the typed result and the typed winner.\n";
                        alert(errorMessages);
                        event.preventDefault();
                        return false;
                    } else if (firstGameWinner == secondGameWinner && firstGameWinner == $winner.val()) {
                        return true;
                    } else {
                        if ($hostScoreThirdGame.val() == EMPTY && $guestScoreThirdGame.val() == EMPTY) {
                            errorMessages += "Must be have and third game for determination of the winner.\n";
                            alert(errorMessages);
                            event.preventDefault();
                            return false;
                        }

                        var resultTGameHost = parseInt($hostScoreThirdGame.val());
                        var resultTGameGuest = parseInt($guestScoreThirdGame.val());

                        if (resultTGameHost == resultTGameGuest) {
                            errorMessages += "Result is incorrect. Please fix it.";
                            alert(errorMessages);
                            event.preventDefault();
                            return false;
                        }

                        var thirdGameWinner = resultTGameGuest > resultTGameHost ? winnerEnum.GUEST : winnerEnum.HOST;

                        if ((thirdGameWinner == firstGameWinner && thirdGameWinner != $winner.val()) ||
                            (thirdGameWinner == secondGameWinner && thirdGameWinner != $winner.val())) {
                            errorMessages += "A mismatch between the typed result and the typed winner.\n";
                            alert(errorMessages);
                            event.preventDefault();
                            return false;
                        }

                        return true;
                    }
                } else {
                    errorMessages += "You did not specify winner, but you are not enter results.\n";
                    alert(errorMessages);
                    event.preventDefault();
                    return false;
                }
            }
            return true;
        }

        function init() {
            fillDataInModalMatch();

            jQuery(".closeBtn").on("click", function(){clearModalMatch()});
            jQuery(".close").on("click", function(){clearModalMatch()});

            jQuery("form[name='match']").submit(function(event) {
                return isValid(event);
            });

            $(document).keyup(function(e) {
                if (e.keyCode == 27) { clearModalMatch(); }
            });
        }
    };

    this.parseArrayToMatchesFromJSON = function(json){
        var UNDEFINED = 'undefined';
        var jsonObject = jQuery.parseJSON(json);
        var collectionStages = [];
        if (typeof(jsonObject.stageOfTournament) !== UNDEFINED && jQuery.isArray(jsonObject.stageOfTournament)){
            for (var i =0; i < jsonObject.stageOfTournament.length; i++) {
                var stageOfTournament = {stage : "", collectionMatches : []};
                stageOfTournament.stage = jsonObject.stageOfTournament[i].stage;
                var collectionMatches = [];
                for (var j = 0; j < jsonObject.stageOfTournament[i].matches.length; j++) {
                    collectionMatches[j] = new TennisTour.Model.Match(jsonObject.stageOfTournament[i].matches[j]);
                }
                stageOfTournament.collectionMatches = collectionMatches;
                collectionStages[i] = stageOfTournament;
            }
        }
        return collectionStages;
    };

    /**
     *
     * @param input {
     * deployId : string,
     * collectionStages : array from object {
         *  stage : string,
         *  collectionMatches : array from Match
     * }
     */
    this.showAllMatches = function(input){
        var UNDEFINED = 'undefined';
        var noMatchesLabel = '<h1 style="text-align: center;">There is no games yet.</h2>';
        var isAdmin = !!(jQuery("#admin").text() == "true");
        var stagesPattern = '<div class="accordion" id="accordion2">';

        if (typeof(input.deployId) == UNDEFINED || typeof(input.collectionStages) == UNDEFINED ||
            !jQuery.isArray(input.collectionStages)) {
            return;
        }

        if (input.collectionStages.length == 0) {
            jQuery('#' + input.deployId).append(noMatchesLabel);
            return;
        }

        for(var i = 0; i < input.collectionStages.length; i++){
            stagesPattern += createModelOfMatches(input.collectionStages[i], i, !!(i == 0));
        }

        stagesPattern += '</div>';

        jQuery('#' + input.deployId).html(stagesPattern);

        var matchService = new TennisTour.Service.MatchesService();

        // Create Event to popule manage form when is clicked to specific button
        jQuery(".manageMatchBtn").on("click", function() {
            var matchId = parseInt(jQuery(this).find('span').text());
            matchService.manageMatch(findMatch(input.collectionStages, matchId));
        });

        /**
         * Find specific Match into collection from matches by specific id
         * @param collectionGroupStages : array from {stage : string, collectionMatches : array from Match}
         * @param matchId int
         * @returns {TennisTour.Model.Match} | null
         */
        function findMatch(collectionGroupStages, matchId) {
            for (var i = 0; i < collectionGroupStages.length; i++) {
                var collectionMatches = collectionGroupStages[i].collectionMatches;

                for (var j = 0; j < collectionMatches.length; j++) {
                    if (collectionMatches[j].id == matchId) {
                        return collectionMatches[j];
                    }
                }
            }
            return null;
        }


        function createModelOfMatches(stageOfTournament, collapseNum, isCollapse){
            var pattern = '<div class="accordion-group">' +
                '<div class="accordion-heading">'+
                    '<a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion2"' +
                    ' href="#collapse' + collapseNum + '"> Stage of tournament: ' + stageOfTournament.stage + '</a>' +
                '</div>' +
                '<div id="collapse' + collapseNum + '" class="accordion-body collapse ';
            pattern += isCollapse ? "in" : "";
            pattern += '"><div class="accordion-inner collectionMatches">';

            for(var i = 0; i < stageOfTournament.collectionMatches.length; i++){
                pattern += createModelOfMatch(stageOfTournament.collectionMatches[i]);
            }

            pattern += '</div></div></div>';

            return pattern;

            /**
             * Crate model of Match
             * @param match TennisTour.Model.Match
             * @returns {string}
             */
            function createModelOfMatch(match) {
                var matchPattern = '<section class="matchesContent" style="width: 570px; float:left;">';
                var isToday = $.datepicker.formatDate("dd/mm/yy", match.date) == $.datepicker.formatDate("dd/mm/yy", new Date());
                if (match.winner == null) {
                    matchPattern += createModelOfPlayer('hostPlayer', null, match.hostPlayer, isToday);
                    matchPattern += createModelOfPlayer('guestPlayer', null, match.guestPlayer, isToday);
                } else if (match.winner == TennisTour.Model.WinnerEnum.HOST) {
                    matchPattern += createModelOfPlayer('hostPlayer', true, match.hostPlayer, isToday);
                    matchPattern += createModelOfPlayer('guestPlayer', false, match.guestPlayer, isToday);
                } else {
                    matchPattern += createModelOfPlayer('hostPlayer', false, match.hostPlayer, isToday);
                    matchPattern += createModelOfPlayer('guestPlayer', true, match.guestPlayer, isToday);
                }

                matchPattern += createModelOfResult(match);

                if (isAdmin && match.winner == null) {
                    matchPattern += '<a href="#manageMatch" class="manageMatchBtn" data-toggle="modal"><button class="btn">Manage<span style="display:none;">' +
                       match.id + '</span></button></a>';
                }

                matchPattern += '</section>';

                return matchPattern;

                /**
                 * Create model of Player
                 * @param cssClassTypePlayer name of css class for specific Player
                 * @param isAWinner Whether current Player is winner or not
                 * @param player TennisTour.Model.Player
                 * @returns {string}
                 */
                function createModelOfPlayer(cssClassTypePlayer, isAWinner, player, isToday) {
                    var playerPattern = '<div class="'+ cssClassTypePlayer + ' ';
                    playerPattern += isAWinner == null ? '' : isAWinner ? ' winner' : ' losses';
                    playerPattern += '"><div style="overflow: hidden; width: 100%; height: 160px;">';
                    if (isAWinner) {
                        playerPattern += '<img src="/img/tick.png" style="width: 36px; position: absolute; margin-left: 2px;">';
                    }
                    playerPattern += '<img style="min-height: 160px; width: auto;" ';
                    playerPattern += isAWinner == null && !isToday ? ' class="greyBackground" ' : '';
                    playerPattern += 'src="' + player.pathToPicture + '"/></div>'+
                        '<table class="matchesTable">' +
                        '<tr>' + '<td>' + 'Name :' + '</td>' + '<td style="margin-left: -20px; position: absolute;">' + player.name + '</td>' + '</tr>' +
                        '<tr>' + '<td>' + 'Job :' + '</td>' + '<td style="margin-left: -27px; position: absolute;">' + player.jobPosition + '</td>' + '</tr>' +
                        '<tr>' + '<td>' + 'Wins :' + '</td>' + '<td>' + player.numberWinners + '</td>' + '</tr>' +
                        '<tr>' + '<td>' + 'Losses :' + '</td>' + '<td>' + player.numberLosses + '</td>' + '</tr>' +
                        '<tr>' + '<td style="width: 110px; position: absolute;">+/- difference points :' + '</td>' + '<td>' + player.differencePoints + '</td>' + '</tr>' +
                        '</table></div>';

                    return playerPattern;
                }

                /**
                 *
                 * Create model of Results
                 * @param match {TennisTour.Model.Match}
                 * @returns {string}
                 */
                function createModelOfResult(match) {
                    var resultService = new TennisTour.Service.ResultService();
                    var resultPattern = '<section class="results result' + match.id + '">';

                    if (match.CollectionResults != null) {
                        /** @var {TennisTour.Model.Result} */
                        var firstGame = resultService.getResultByGame(match.CollectionResults, TennisTour.Model.GameEnum.FIRST);
                        resultPattern += '<article class="fGame">First Game: ' +
                            '<div class="scoreTwo ';
                        resultPattern += firstGame.hostScore < firstGame.guestScore ? "winnerOfScore" : "lossesOfScore";
                        resultPattern += '">';
                        resultPattern += firstGame.guestScore != null ? firstGame.guestScore: '';
                        resultPattern += '</div> '+

                            '<div class="scoreOne ';
                        resultPattern += firstGame.hostScore > firstGame.guestScore ? "winnerOfScore" : "lossesOfScore";
                        resultPattern += '">';
                        resultPattern += firstGame.guestScore != null ? firstGame.hostScore: '';
                        resultPattern += '</div></article>';

                        /** @var {TennisTour.Model.Result} */
                        var secondGame = resultService.getResultByGame(match.CollectionResults, TennisTour.Model.GameEnum.SECOND);
                        resultPattern += '<article class="sGame">Second Game: ' +
                            '<div class="scoreTwo ';
                        resultPattern += secondGame.hostScore < secondGame.guestScore ? "winnerOfScore" : "lossesOfScore";
                        resultPattern += '">';
                        resultPattern += secondGame.guestScore != null ? secondGame.guestScore: '';
                        resultPattern += '</div> '+

                            '<div class="scoreOne ';
                        resultPattern += secondGame.hostScore > secondGame.guestScore ? "winnerOfScore" : "lossesOfScore";
                        resultPattern += '">';
                        resultPattern += secondGame.guestScore != null ? secondGame.hostScore: '';
                        resultPattern += '</div></article>';

                        /** @var {TennisTour.Model.Result} */
                        var thirdGame = resultService.getResultByGame(match.CollectionResults, TennisTour.Model.GameEnum.THIRD);
                        resultPattern += '<article class="tGame">Third Game: ' +
                            '<div class="scoreTwo ';
                        if (thirdGame != null) {
                            resultPattern += thirdGame.hostScore < thirdGame.guestScore ? "winnerOfScore" : "lossesOfScore";
                            resultPattern += '">';
                            resultPattern += thirdGame.guestScore != null ? thirdGame.guestScore: '';
                        } else {
                            resultPattern += '">';
                        }
                        resultPattern += '</div> '+

                            '<div class="scoreOne ';
                        if (thirdGame != null) {
                            resultPattern += thirdGame.hostScore > thirdGame.guestScore ? "winnerOfScore" : "lossesOfScore";
                            resultPattern += '">';
                            resultPattern += thirdGame.guestScore != null ? thirdGame.hostScore: '';
                        } else {
                            resultPattern += '">';
                        }

                        resultPattern += '</div></article>';

                    } else {
                        resultPattern += '<article class="fGame">First Game: ' +
                             '<div class="scoreOne"></div><div class="scoreTwo"></div></article>';
                        resultPattern += '<article class="sGame">Second Game: ' +
                            '<div class="scoreOne"></div><div class="scoreTwo"></div></article>';
                        resultPattern += '<article class="tGame">Third Game: ' +
                            '<div class="scoreOne"></div><div class="scoreTwo"></div></article>';
                    }

                    if (!isAdmin) {
                        if (match.date == null) {
                            resultPattern += '<article class="fGame" style="font-size: 7pt;">There is no agreed date for the game</article>';
                        } else if ($.datepicker.formatDate("dd/mm/yy", match.date) == $.datepicker.formatDate("dd/mm/yy", new Date())) {
                            resultPattern += '<article class="fGame" style="font-size: 12pt; color:#5bb75b; text-shadow: 1px 1px 2px black;">Match is today!</article>';
                        } else if (match.CollectionResults == null) {
                            resultPattern += '<article class="fGame" style="font-size: 7pt; text-shadow: 1px 1px 2px black;">The match will be on date: ' +
                                $.datepicker.formatDate("dd/mm/yy", match.date) + '</article>';
                        } else {
                            resultPattern += '<article class="fGame" style="font-size: 8pt;">Date of game: ' +
                                $.datepicker.formatDate("dd/mm/yy", match.date) + '</article>';
                        }
                    }

                    resultPattern += '</section>';

                    return resultPattern;
                }
            }
        }
    }
};

TennisTour.Service.ResultService = function() {
    /**
     * Get Result by pointed gameEnum
     * @param collectionResults array from Result
     * @param gameEnum string
     * @returns an {TennisTour.Model.Result}
     */
    this.getResultByGame = function(collectionResults, gameEnum) {
        for (var i = 0; i < collectionResults.length; i++) {
            if (collectionResults[i].game == gameEnum) {
                return collectionResults[i];
            }
        }
        return null;
    }

};

/**
 * This represent the service class for a admin panel
 */
TennisTour.Service.ManagementService = function() {

    /**
     * Show all players which are created, plus a button for creation of new one
     * @param collectionPlayers array from {TennisTour.Model.Player}
     * @returns void
     */
    this.managePlayers = function(collectionPlayers) {
        var createNewPlayer = '<a href="#addPlayer" data-toggle="modal">' +
                                    '<img src="img/plus.png" title="Add Player" class="addBtnPlus"/>' +
                              '</a>';

        var pattern = '<ul class="thumbnails">';

        for (var i = 0; i < collectionPlayers.length; i++) {
            pattern += '<li class="span2">' + createModelOfPlayer(collectionPlayers[i]) + '</li>';
        }

        pattern += '<li class="span2">' + createNewPlayer + '</li></ul>';

        jQuery('#showPlayers').html(pattern);
    };

    this.manageGroups = function(collectionPlayers, urlForSave) {
        displayPlayers(collectionPlayers);

        var $playersBox = $('#playersToGroup');
        var collectionGroups = [];
        var playerService = new TennisTour.Service.PlayerService();

        // let the gallery items be draggable
        $( "li", $playersBox ).draggable({
            revert: "invalid", // when not dropped, the item will revert back to its initial position
            containment: "document",
            helper: "clone",
            cursor: "move"
        });

        $('#addGroupBtn').on('click', function() {
            var groupName = prompt("Enter group name:");
            if (groupName != null || groupName != "") {
                var newGroup = new TennisTour.Model.Group();
                newGroup.name = groupName;
                collectionGroups.push(newGroup);
                displayNewGroup(newGroup);
            }
        });

        $('#createGroups').on('click', function() {
            var collectionGroupsJSON = jQuery.toJSON(collectionGroups);
            var url = urlForSave + '?collectionGroupsJSON=' + collectionGroupsJSON;
            $(location).attr('href',url);
        });

        /**
         * Display new group
         * @param group {TennisTour.Model.Group}
         */
        function displayNewGroup(group) {
            var pattern = '<article class="group">' +
                '<h5>Group ' + group.name + '</h5>' +
                '<div style="overflow: auto;" id="' + group.name + '" class="ui-widget-content ui-state-default"></div>' +
                '</article>';
            jQuery('#groups').append(pattern);

            // let the trash be droppable, accepting the gallery items
            var groupBox = jQuery('#' + group.name);
            groupBox.droppable({
                accept: "#playersToGroup > li",
                activeClass: "ui-state-highlight",
                drop: function( event, ui ) {
                    var playerId = parseInt(ui.draggable.find('.id').text());
                    var player = playerService.getPlayerById(collectionPlayers, playerId);
                    var groupStats = new TennisTour.Model.GroupStats();
                    groupStats.player = player;
                    group.CollectionGroupStats.push(groupStats);
                    deleteImage( ui.draggable, groupBox);
                }
            });
        }

        // image deletion function
        function deleteImage( $item , target) {
            $item.fadeOut(function() {
                var $list = $( "ul", target ).length ?
                    $( "ul", target ) :
                    $( "<ul class='class=groupsPlayers ui-helper-reset'/>" ).appendTo( target );

                $item.find( "a.ui-icon-trash" ).remove();
                $item.appendTo( $list ).fadeIn(function() {
                    $item
                        .animate({ width: "75px", height: "100px", marginBottom: "5px" })
                        .find('div').animate({ height: "45px" })
                        .find( "img").animate({ width: "40px", marginLeft : "5px" })
                        .find('h5').animate({fontSize : "8pt"});
                });
            });
        }

        /**
         * Show all players which are in colleciton
         * @param collectionPlayers
         */
        function displayPlayers(collectionPlayers) {
            var pattern = '<ul id="playersToGroup" class="playersToGroup">';

            for (var i = 0; i < collectionPlayers.length; i++) {
                pattern += '<li class="span2 ui-widget-content">' +
                                createModelOfPlayer(collectionPlayers[i]) +
                           '</li>';
            }

            pattern += '</ul>';

            jQuery("#groupsPlayers").html(pattern);
        }

    };

    /**
     * Create a model of a Player
     * @param player {TennisTour.Model.Player}
     * returns {string}
     */
    function createModelOfPlayer(player) {
        return '<div class="thumbnail">' +
            '<div style="overflow:  hidden; width: 160px; height: 160px">' +
            '<img src="' + player.pathToPicture  + '"/>' +
            '</div>' +
            '<h5 style="text-align: center;">' + player.name + '</h5>'+
            '<article style="display: none; class="info">' +
            '<span class="id">' + player.id + '</span>' +
            '<span class="name">' + player.name + '</span>' +
            '<span class="jobPosition">' + player.jobPosition + '</span>' +
            '<span class="pathToPicture">' + player.pathToPicture + '</span>' +
            '<span class="numberWinners">' + player.numberWinners + '</span>' +
            '<span class="numberLosses">' + player.numberLosses + '</span>' +
            '<span class="differencePoints">' + player.differencePoints+ '</span>' +
            '</article></div>';
    }


};

/**
 * This represent the service class for a {2link TennisTour.Model.Player} model
 */
TennisTour.Service.PlayerService = function() {

    /**
     * Parse JSON object which represent collection from objects to
     * collection from {@link TennisTour.Model.Player}
     * @param JSON collection from objects
     * @returns {Array}
     */
    this.parseJSONCollectionToPlayersCollection = function(JSON) {
        var jsonCollection = jQuery.parseJSON(JSON);
        var playerCollection = [];

        for (var i = 0; i < jsonCollection.length; i++) {
            playerCollection.push(new TennisTour.Model.Player(jsonCollection[i]));
        }

        return playerCollection;
    };

    /**
     * Return an instance of Player if exist in collectionPlayers by its id
     * @param collectionPlayers
     * @param id
     * @returns {TennisTour.Model.Player | null}
     */
    this.getPlayerById = function(collectionPlayers, id) {
        for (var i = 0; i < collectionPlayers.length; i++) {
            if (collectionPlayers[i].id == id) {
                return collectionPlayers[i];
            }
        }
        return null;
    };

    /**
     * Show all players which are created, plus a button for creation of new one
     * @param collectionPlayers array from {TennisTour.Model.Player}
     * @returns void
     */
    this.showAll = function(collectionPlayers) {

        var pattern = '<ul class="players">';

        for (var i = 0; i < collectionPlayers.length; i++) {
            pattern += '<li class="span2">' + createModelOfPlayer(collectionPlayers[i]) + '</li>';
        }

        jQuery('#content').append(pattern);

        /**
         * Create a model of a Player
         * @param player {TennisTour.Model.Player}
         * returns {string}
         */
        function createModelOfPlayer(player) {
            var playerPattern = '<div style="box-shadow: 1px 2px 10px black;">' +
                '<div style="overflow: hidden; width: 100%; height: 160px;">';
            playerPattern += '<img style="min-height: 160px; width: auto;" ';
            playerPattern += 'src="' + player.pathToPicture + '"/></div>'+
                '<table class="matchesTable" style="color: white;">' +
                '<tr>' + '<td>' + 'Name :' + '</td>' + '<td style="margin-left: -20px; position: absolute;">' + player.name + '</td>' + '</tr>' +
                '<tr>' + '<td>' + 'Job :' + '</td>' + '<td style="margin-left: -27px; position: absolute;">' + player.jobPosition + '</td>' + '</tr>' +
                '<tr>' + '<td>' + 'Winners :' + '</td>' + '<td>' + player.numberWinners + '</td>' + '</tr>' +
                '<tr>' + '<td>' + 'Losses :' + '</td>' + '<td>' + player.numberLosses + '</td>' + '</tr>' +
                '<tr>' + '<td style="width: 110px; position: absolute;">+/- difference points :' + '</td>' + '<td>' + player.differencePoints + '</td>' + '</tr>' +
                '</table></div>';

            return playerPattern;
        }
    };

    /**
     * Show winners standing if application is finished
     * @param object {first : Player, second : Player, third : Player, bestScorer : Player}
     */
    this.showWinners = function(object) {
        if (object != null) {
            /* Fill data for best scorer */
            jQuery('#goalMyster .player>img').attr('src', object.bestScorer.pathToPicture);
            jQuery('#goalMyster .player>span').text(object.bestScorer.name);

            /* Fill data first place */
            jQuery('#firstPlace .player>img').attr('src', object.first.pathToPicture);
            jQuery('#firstPlace .player>span').text(object.first.name);

            /* Fill data second place */
            jQuery('#secondPlace .player>img').attr('src', object.second.pathToPicture);
            jQuery('#secondPlace .player>span').text(object.second.name);

            /* Fill data third place */
            jQuery('#thirdPlace .player>img').attr('src', object.third.pathToPicture);
            jQuery('#thirdPlace .player>span').text(object.third.name);

            jQuery('#winners').show();
        }
    }
};